/**
 * 
 */
Ext.ns("Ext.lams");
/**
 * 表单
 * 
 * @class Ext.lams.StudentInfoForm
 * @extends Ext.form.FormPanel
 */
Ext.lams.StudentInfoForm = Ext.extend(Ext.form.FormPanel, {
	constructor : function(_cfg) {
		Ext.apply(this, _cfg || {});
		Ext.lams.StudentInfoForm.superclass.constructor.call(this, {
					layout : "form",
					frame : true,
					fileUpload : true
				});
	},
	initComponent : function() {
		this.items = [{
					xtype : "hidden",
					name : "STUDENT_ID"
				}, {
					layout : 'column',
					items : [{
						layout : 'form',
						columnWidth : .6,
						defaultType : 'textfield',
						defaults : {
							anchor : "90%"
						},
						labelWidth : 65,
						items : [{
									fieldLabel : '姓名',
									allowBlank : false,
									blankText : "姓名不能为空",
									name : 'STUDENT_NAME'
								}, {
									xtype : "combo_sex",
									hiddenName : 'GENDER',

									allowBlank : false,
									blankText : "请选择性别"
								}, {
									fieldLabel : '学号',
									name : 'STUDENT_NO',
									allowBlank : false,
									blankText : '学号不能为空'
								}, {
									fieldLabel : "年龄",
									// name : 'stu_age',
									readOnly : true
								}, {
									xtype : "datefield",
									fieldLabel : "出生年月",
									name : 'BIRTH_DATE',
									value : new Date(),
									editable : false,
									format : "Y-m-d",
									listeners : {
										"blur" : function(_df) {
											var arg = _df.ownerCt.find(
													'fieldLabel', '年龄')[0];
											var value = new Date()
													.getFullYear()
													- _df.getValue()
															.getFullYear() == 0
													? 1
													: new Date().getFullYear()
															- _df
																	.getValue()
																	.getFullYear();
											arg.setValue(value);
										}
									}
								}, {
									fieldLabel : '监护人姓名',
									name : 'GUARDIAN',
									allowBlank : false,
									blankText : '请填写监护人'
								}, {
									fieldLabel : '监护人电话',
									name : 'GUARDIAN_PHONE',
									allowBlank : false,
									blankText : '请填写监护人联系方式'
								}, {
									xtype : "combo_school",
									hiddenName : "SCHOOL_ID",
									allowBlank : false,
									// autoLoad:false,
									blankText : '请选择学校',
									listeners : {
										select : function(self, sch) {
											var stu_class = self.ownerCt.ownerCt
													.find('fieldLabel', '班级')[0];
											// stu_class.text="";
											stu_class.setValue("");
										}
									}
								}, {
									xtype : "combo_class",
									hiddenName : "CLASS_ID",
									allowBlank : false,
									// autoLoad : false,
									blankText : '请选择班级',
									listeners : {
										beforequery : function(qEvent) {
											var school = qEvent['combo'].ownerCt.ownerCt
													.find('fieldLabel', '学校')[0];
											qEvent['query'] = school.getValue()
													|| '-1';
											qEvent['forceAll'] = true;
											qEvent['cancel'] = false;
											return true;
										}
									}
								}]
					}, {
						columnWidth : .4,
						layout : 'form',
						labelWidth : 45,
						defaults : {
							anchor : "98%"
						},
						items : [{
									fieldLabel : '照片',
									xtype : "textfield",
									inputType : 'image',
									width : 150,
									height : 200,
									listeners : {
										"render" : function(_field) {
											_field.el.dom.src = "../avatr/000000.jpg";
										}
									}
								}, {
									xtype : 'fileuploadfield',
									// id : 'form-file',
									emptyText : '请选择要上传的照片',
									fieldLabel : '照片',
									// vtype:'checkImage',
									name : 'PHOTO',
									buttonText : '',
									buttonCfg : {
										iconCls : 'silk-image-add'
									},
									listeners : {
										"fileselected" : function(a, b) {

										}
									}
								}]
					}]
				}, {
					layout : 'form',
					defaults : {
						anchor : "95%"
					},
					labelWidth : 65,
					defaultType : 'textfield',
					items : [{
								fieldLabel : '家庭住址',
								name : 'ADDRESS'
							}, {
								fieldLabel : '备注',
								xtype : 'textarea',
								name : 'REMARK'
							}]
				}];
		Ext.lams.StudentInfoForm.superclass.initComponent.call(this);
	},
	getValue : function() {
		if (this.getForm().isValid())
			return new Ext.data.Record(this.getForm().getValues());
		else
			throw Error("表单填写出错");
	},
	setValue : function(_r) {
		this.getForm().loadRecord(_r);
		if (!_r.data["PHOTO"] || _r.data["PHOTO"] == "")
			this.find("fieldLabel", "照片")[0].el.dom.src = "../avatr/000000.jpg";
		else
			this.find("fieldLabel", "照片")[0].el.dom.src = "../avatr/"
					+ _r.data["PHOTO"];
	},
	clear : function() {
		this.getForm().reset();
	},
	submit : function(fn) {
		if (this.getForm().isValid()) {
			this.getForm().submit({
						// clientValidation: true,
						waitMsg : "正在保存数据...",
						method : "POST",
						// isUpload:true,
						url : "addOrUpdateStudentAction.action",
						success : function(form, action) {
							fn(form, action);
						},
						faild : function(form, action) {
							fn(form, action);
						}
					});
		}
	}
});

/**
 * 列表
 * 
 * @class Ext.lams.StudentGrid
 * @extends Ext.grid.GridPanel
 */
Ext.lams.StudentGrid = Ext.extend(Ext.grid.GridPanel, {
			constructor : function(_cfg) {
				if (!_cfg)
					_cfg = {};
				Ext.apply(this, _cfg);
				Ext.lams.StudentGrid.superclass.constructor.call(this, {
							frame : true,
							loadMask : {
								msg : '正在载入数据,请稍等...'
							},
							listeners : {
								rowdblclick : function(g) {
									var r = g.getSelectionModel().getSelected();
									this.fireEvent("rowdb", this, r);
									// alert(d.data);
								}
							}
						});
				this.addEvents("rowdb");
				this.addEvents("edit");
				this.addEvents("delete");
			},
			initComponent : function() {
				var me = this;
				var _store = new Ext.data.JsonStore({
							proxy : new Ext.data.HttpProxy({
										url : "queryStudentAction.action",
										method : "GET",
										baseParams : {}
									}),
							totalProperty : "totalCount",
							root : "data",
							fields : [{
										name : "STUDENT_ID"
									}, {
										name : "STUDENT_NAME"
									}, {
										name : "STUDENT_NO"
									}, {
										name : "CLASS_NAME"
									}, {
										name : "BIRTH_DATE"
									}, {
										name : "GENDER"
									}, {
										name : "GUARDIAN_PHONE"
									}, {
										name : "ADDRESS"
									}, {
										name : "GUARDIAN"
									}, {
										name : "CLASS_ID"
									}, {
										name : "SCHOOL_NAME"
									}, {
										name : "SCHOOL_ID"
									}, {
										name : "PHOTO"
									}]
						});
				var _sm = new Ext.grid.RowSelectionModel({
							singleSelect : true
						});
				var _cm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(),
						{
							header : "学生编号",
							hidden : true,
							dataIndex : "STUDENT_ID"
						}, {
							header : "姓名",
							dataIndex : "STUDENT_NAME"
						}, {
							header : "学号",
							dataIndex : "STUDENT_NO"
						}, {
							header : "所属学校",
							dataIndex : "SCHOOL_NAME"
						}, {
							header : "所属班级",
							dataIndex : "CLASS_NAME"
						}, {
							header : "出生年月",
							dataIndex : "BIRTH_DATE"
						}, {
							header : "性别",
							dataIndex : "GENDER"
						}, {
							header : "监护人",
							dataIndex : "GUARDIAN"
						}, {
							header : "监护人电话",
							dataIndex : "GUARDIAN_PHONE"
						}, {
							header : "家庭住址",
							// width : 200,
							dataIndex : "ADDRESS"
						}, {
							header : "学校编号",
							hidden : true,
							dataIndex : "SCHOOL_ID"
						}, {
							header : "班级编号",
							hidden : true,
							dataIndex : "CLASS_ID"
						}, {
							header : "照片",
							hidden : true,
							width : 180,
							dataIndex : "PHOTO"
						}, {
							header : "",
							width : 30,
							renderer : function(v, d, r, ridx, cidx, s) {
								return me.edit_render(r);
							}
						}, {
							header : "",
							width : 30,
							renderer : function(v, d, r, ridx, cidx, s) {
								return me.delete_render(r);
							}
						}]);

				var bbar = new Ext.lams.comp.PagingToolbar({
							store : _store
						});
				Ext.apply(this, {
							store : _store,
							cm : _cm,
							sm : _sm,
							bbar : bbar
						});
				Ext.lams.StudentGrid.superclass.initComponent.call(this);
			},
			getSelectRow : function() {
				var sel = this.getSelectionModel();
				if (sel.getCount() == 0)
					throw new Error("未选中某条记录");
				return sel.getSelected();
			},
			addStudenRow : function(_r) {
				this.getStore().add(_r);
			},
			deleteStudentRow : function() {
				try {
					var sel = this.getSelectRow();
					var grid = this;
					Ext.Ajax.request({
								url : '',
								method : 'POST',
								params : {

					}			,
								success : function() {
									grid.getStore().remove(sel);
								}
							});
				} catch (_err) {
					// Ext.Msg.alert("Error", _err.message);
					H.Msg.error(_err.message);
				}
			},
			modifySelectRow : function(_r) {
				try {
					var _sr = this.getSelectRow();
					var _data = _sr.data;
					for (var _i in _data) {
						_sr.set(_i, _r.get(_i));
					}
					_sr.commit();
				} catch (_err) {
					// Ext.Msg.alert("Error", _err.message);
					H.Msg.error(_err.message);
				}
			},
			edit_render : function(recode) {
				var me = this;
				var contentId = Ext.id();
				var btn = createGridButton.defer(1, this, [contentId]);
				function createGridButton() {
					return new Ext.Button({
								iconCls : 'silk-user-edit',
								// width:16,
								tooltip : '编辑',
								handler : function() {
									me.fireEvent('edit', recode, me);
								}
							}).render(document.body, contentId);
				}
				return ('<div id="' + contentId + '"/>');
			},
			delete_render : function(recode) {
				var me = this;
				var contentId = Ext.id();
				var btn = createGridButton.defer(1, this, [contentId]);
				function createGridButton() {
					return new Ext.Button({
								iconCls : 'silk-user-delete',
								tooltip : '删除',
								handler : function() {
									me.fireEvent('delete', recode, me);
								}
							}).render(document.body, contentId);
				}
				return ('<div id="' + contentId + '"/>');
			}
		});
/**
 * 主界面
 * 
 * @class Ext.lams.StudentManagerPanel
 * @extends Ext.Panel
 */
Ext.lams.StudentManagerPanel = Ext.extend(Ext.Panel, {
	grid : {},
	constructor : function(_cfg) {
		if (!_cfg)
			_cfg = {};
		Ext.apply(this, _cfg);
		Ext.lams.StudentManagerPanel.superclass.constructor.call(this);
		this.grid.on("rowdb", this.onRowdbClick, this);
		this.grid.on("edit", this.onEditHandler, this);
		this.grid.on("delete", this.onDeleteHandler, this);
	},
	initComponent : function() {
		var me = this;
		var h = new Ext.form.FormPanel({
			region : "north",
			height : 40,
			split : true,
			frame : true,
			collapseMode : 'mini',
			layout : "form",
			items : [{
				anchor : '100%',
				baseCls : 'x-plain',
				layout : 'hbox',
				layoutConfig : {
					padding : 5
				},
				defaults : {
					margins : '0 15 0 0'
				},
				// defaults:{labelWidth:65},
				items : [{
					layout : "form",
					labelWidth : 35,
					flex : .3,
					items : [{
						xtype : "combo_school",
						hiddenName : "SCHOOL_ID",
						// autoLoad:true,
						// hiddenValue:"-1",
						listeners : {
							select : function(self, sch) {
								var stu_class = self.ownerCt.ownerCt.find(
										'fieldLabel', '班级')[0];
								// stu_class.lastSelectionText=" ";
								stu_class.setValue("");
								// stu_class.hiddenValue="-1";
							}
						}
					}]
				}, {
					layout : "form",
					labelWidth : 35,
					flex : .3,
					items : [{
						xtype : "combo_class",
						hiddenName : "CLASS_ID",
						// autoLoad:true,
						listeners : {
							beforequery : function(qEvent) {
								var school = qEvent['combo'].ownerCt.ownerCt
										.find('fieldLabel', '学校')[0];
								qEvent['query'] = school.getValue() || '-1';
								qEvent['forceAll'] = true;
								qEvent['cancel'] = false;
								return true;
							}
						}
					}]
				}, {
					layout : "form",
					labelWidth : 35,
					flex : .3,
					items : [{
						xtype : "xauto",
						fieldLabel : "学生",
						hiddenName : "STUDENT_ID",
						hiddenValue : "-1",
						fields : [{
									name : "STUDENT_ID"
								}, {
									name : "STUDENT_NO"
								}, {
									name : "STUDENT_NAME"
								}],
						valueField : "STUDENT_ID",
						displayField : "STUDENT_NAME",
						tpl : new Ext.XTemplate(
								'<tpl for="."><div class="x-combo-list-item">',
								'{STUDENT_NO}--{STUDENT_NAME}', '</div></tpl>'),
						// sqlCode : "STU_COMPLETE",
						params : {
							sqlCode : 'STU_COMPLETE'
						},
						itemSelector : 'div.x-combo-list-item',
						emptyText : "输入学生姓名或学号"
					}]
				}, {
					xtype : "btn_query",
					handler : function() {
						var btn = this;
						btn.disable();
						var _params = me.form.getForm().getValues();
						// alert(_params.stu_class);
						var ds = me.grid.getStore();
						var pagingbar = me.grid.getBottomToolbar();
						ds.baseParams = _params;
						ds.load({
									params : {
										start : 0,
										limit : pagingbar.pageSize
									},
									callback : function(a, b) {
										btn.enable();
									}
								});
					}
				}, {
					xtype : "btn_new",
					handler : function() {
						me.editWin.form.clear();
						me.editWin.show();
						me.editWin.form.find('fieldLabel', '照片')[0].el.dom.src = "../avatr/000000.jpg";
					}
				}, {
					flex : .3
				}]
			}]
		});
		this.form = h;

		var center = new Ext.lams.StudentGrid({
					region : "center"
				});
		this.grid = center;
		var sf = new Ext.lams.StudentInfoForm();
		this.infoForm = sf;

		var win = new Ext.Window({
			width : 500,
			title : "学生信息",
			form : this.infoForm,
			closeAction : "hide",
			items : [this.infoForm],
			buttons : [{
				xtype : "btn_save",
				handler : function() {
					me.infoForm.submit(function(_form, action) {
						if (action.result['success']) {
							// Ext.Msg.alert('提示', action.result['message']);
							H.Msg.info(action.result['message'], function() {
								if (action.result.data[0].PHOTOFileName)
									me.infoForm.find('fieldLabel', '照片')[0].el.dom.src = "../aratr/"
											+ action.result.data[0].PHOTOFileName;
								me.editWin.form.clear();
								me.editWin.hide();
								me.grid.getStore().reload();
							});
						}
					});
				}
			}, {
				xtype : "btn_cancel",
				handler : function() {
					me.editWin.form.clear();
					me.editWin.hide();
				}
			}]
		});
		this.editWin = win;
		Ext.apply(this, {
					layout : 'border',
					frame : true,
					items : [h, center]
				});
		Ext.lams.StudentManagerPanel.superclass.initComponent.call(this);
	},
	onRowdbClick : function() {
		try {
			// if(!_r)_r = this.grid.getSelectRow()
			this.editWin.form.clear();
			this.editWin.show();
			this.editWin.form.setValue(this.grid.getSelectRow());

		} catch (_err) {
			// Ext.Msg.alert("Error", _err.message);
			H.Msg.error(_err.message);
		}
	},
	onEditHandler : function(_r) {
		this.editWin.form.clear();
		this.editWin.show();
		this.editWin.form.setValue(_r);
	},
	onDeleteHandler : function(_r) {
		// Ext.Msg.alert(_r.data['STUDENT_NAME']);
		this.grid.getStore().remove(_r);
	}
});
